/* eslint-disable no-shadow */
import React, { useState, useMemo } from 'react';
import { useSelector } from 'dva';
import { useAntdTable, useDebounceFn } from 'ahooks';
import { Form, Table, Input, Button, Upload, message } from 'antd';
import { getMixInList } from '@/services/setup';
import MixInModal from '@/components/_pages/Post/Setup/MixInStorage/MixInModal';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

const FormItem = Form.Item;

const MixInStorage = props => {
  const { user = {} } = useSelector(state => state);
  const { currentUser: { quickLoginType } = {} } = user || {};
  const { form } = props;
  const { getFieldDecorator, validateFields } = form;

  const [visible, setVisible] = useState(false);
  const [cm_id, setCmId] = useState('');
  const [uploading, setUploading] = useState(false);

  const getTableList = async (params, formData) => {
    const { current, pageSize } = params;

    const result = await getMixInList({
      page: current,
      pageSize,
      ...formData,
    });

    return result;
  };

  const { tableProps, search, loading } = useAntdTable(getTableList, {
    defaultPageSize: 20,
    form,
  });

  const { run: onSubmit } = useDebounceFn(
    e => {
      e.preventDefault();
      validateFields(async err => {
        if (err) return;
        search.submit();
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const handelCheckDetail = ({ cm_id } = {}) => {
    setCmId(cm_id);
    setVisible(true);
  };

  const columns = useMemo(
    () => {
      const arr = [
        {
          width: 100,
          align: 'center',
          title: 'id',
          dataIndex: 'cm_id',
        },
        {
          width: 200,
          align: 'center',
          title: '驿站名称',
          dataIndex: 'inn_name',
        },
        {
          width: 150,
          align: 'center',
          title: '驿站账号',
          dataIndex: 'phone',
        },
        {
          width: 150,
          align: 'center',
          title: '入库品牌',
          dataIndex: 'platform',
        },
        {
          width: 200,
          align: 'center',
          title: '更新时间',
          dataIndex: 'update_time',
        },
      ];

      if ([2, 3].includes(quickLoginType)) {
        arr.push({
          width: 100,
          align: 'center',
          title: '详情',
          render: (_, data) => <a onClick={handelCheckDetail.bind(null, data)}>查看详情</a>,
        });
      }

      return arr;
    },
    [quickLoginType],
  );

  const handleChange = () => {
    search.submit();
  };

  const onUpLoadChange = info => {
    setUploading(true);
    if (info.file.status === 'done') {
      setUploading(false);
      if (info.file.response.code != 0) {
        message.error(`${info.file.name} 上传失败：${info.file.response.msg}`);
      } else {
        message.success(`${info.file.name} 上传成功`);
        search.submit();
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
      setUploading(false);
    }
  };

  return (
    <div>
      <Form layout="inline" {...formItemLayout} style={{ marginBottom: 24 }}>
        <FormItem>
          {getFieldDecorator('search')(
            <Input allowClear placeholder="驿站手机号/名称" style={{ width: 250 }} />,
          )}
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={onSubmit} loading={loading}>
            查询
          </Button>
        </FormItem>
        {[2, 3].includes(quickLoginType) && (
          <FormItem>
            <Button
              type="primary"
              onClick={() => {
                handelCheckDetail();
              }}
            >
              添加
            </Button>
          </FormItem>
        )}
        {quickLoginType == 3 && (
          <FormItem>
            <Upload
              action="/Api/YZ/League/complateImport"
              name="file"
              multiple={false}
              accept=".csv"
              showUploadList={false}
              onChange={onUpLoadChange}
            >
              <Button type="primary" icon="upload" loading={uploading}>
                导入
              </Button>
            </Upload>
          </FormItem>
        )}
      </Form>
      <Table
        scroll={{ x: 800 }}
        rowKey="cm_id"
        loading={loading}
        columns={columns}
        {...tableProps}
      />
      <MixInModal
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={handleChange}
        cm_id={cm_id}
      />
    </div>
  );
};

export default Form.create()(MixInStorage);
